package com.mhtool.core.io;

import lombok.experimental.UtilityClass;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author yin
 * @date 2021/12/27 17:20
 * @since 8.0.0
 */
@UtilityClass
public class ZipUtils {
    public static void zip(ZipOutputStream zip, Path root, List<Path> paths) throws IOException {
        for (Path path : paths) {
            Path relativePath = root.relativize(path);
            zip.putNextEntry(new ZipEntry(relativePath.toString()));
            //读取文件并写出
            FileInputStream fileInputStream = new FileInputStream(path.toString());
            try(BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream)) {
                byte[] bytes = new byte[1024];
                int n;
                while ((n = bufferedInputStream.read(bytes)) != -1) {
                    zip.write(bytes, 0, n);
                }
            }
            zip.flush();
            zip.closeEntry();
        }
    }

    public static void main(String[] args) throws IOException {
//        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        String dest = "D:\\tempPrint\\zip.zip";
        Files.delete(Paths.get(dest));
        FileOutputStream fileOutputStream = new FileOutputStream(dest);
        ZipOutputStream zip = new ZipOutputStream(fileOutputStream);
//        ZipOutputStream zip = new ZipOutputStream(outputStream);
        String[] paths = {"D:\\tempPrint\\com\\ruoyi\\project\\system\\controller\\system\\SysRoleController.java",
                "D:\\tempPrint\\views\\system\\sysRole-form.vue",
                "D:\\tempPrint\\views\\system\\sysRole-index.vue"};
        List<Path> collect = Arrays.stream(paths).map(Paths::get).collect(Collectors.toList());
        zip(zip, Paths.get("D:\\tempPrint"), collect);
        StreamUtils.close(zip);
    }
}
